(function($, win, doc, undefined){

	var app = null;
	var editor = null;
	
	function getDialog(){
		
		return  win.parentDialogObj && win.parentDialogObj[""];
	}
	
	function getTransParams(){
				
		return getDialog().getTransParams();
	}
	
	function getFormId(){
		return $.request.getParament('formId');
	}
	
	function getTriggerId(){
		
		return Snail.getEleVar('triggerId', top);
	}
	
	
	/**
	 * 初始化窗口
	 */
	function initWindow(){
		
		var dialog = getDialog();
		
		var dialogSelecter = (dialog ? ('#layui-layer' + dialog.index) : 'div[laytype="dialog"]:last-child');
		
		var dialogEle = $.getElement(dialogSelecter, 0, window.parent.document);
		
		$.setCSS(dialogEle, {
			width: 'calc(100% - 200px)', height: 'calc(100% - 100px)',
			top: '50px', left: '100px'
		});

		var dialogWindow = $.getElement(dialogSelecter + '>div:nth-child(2)', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: 'calc(100% - 105px)'
		});
		
		dialogWindow = $.getElement(dialogSelecter + '>div:nth-child(2)>iframe', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: 'calc(100% - 15px)'
		});
		
		var dialogTitle = $.getElement(dialogSelecter + '>div:first-child', 0, window.parent.document);
		
		$.cleanHtml(dialogTitle);
		$.appendHtml(dialogTitle, '业务单据-触发器');
	}
	
	var jsonCodeMirror = (function (){

		var aesPwd = 'Xxeicq3gknHJEsZR';
		var editor = null;
		var content = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						return;
					}
					
					if(content){
						$.setEleValue('#config_content', content);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#config_content'), {
						mode: 'application/json',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_content){
				
				content = $.aes_decrypt((_content ? decodeURIComponent(_content) : ''), aesPwd);
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(content);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : content), aesPwd);
			},
			getOriginalValue: function(){
				return (editor ? editor.getValue() : content);
			}
		}
	})();
	
	var groovyCodeMirror = (function (){
		
		var editor = null;
		var script = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						return;
					}
					
					if($.isBlank(script)){
						
						$.setEleValue('#script_content', (function(){
							
							var scriptTxt = ['#!/snail/common/utils groovy DIP_TRIGGER_' + $.random20L()];
							scriptTxt.push('');
							scriptTxt.push('import com.seeyon.ctp.common.AppContext;');
							scriptTxt.push('import com.seeyon.apps.snail.APPLogger;');
							scriptTxt.push('import com.seeyon.apps.snail.common.MessageHepler;');
							scriptTxt.push('');
							scriptTxt.push('import snail.common.ClassHelper;');
							scriptTxt.push('import snail.common.ServiceException;');
							scriptTxt.push('import snail.common.utils.StringHelper;');
							scriptTxt.push('import snail.common.utils.JSONHelper;');
							scriptTxt.push('import snail.common.utils.DateHelper;');
							scriptTxt.push('import snail.common.utils.IDHelper;');
							scriptTxt.push('import snail.common.web.HTTPHelper;');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/**');
							scriptTxt.push(' * 业务单据脚本（Groovy）');
							scriptTxt.push(' * ');
							scriptTxt.push(' */');
							scriptTxt.push('static main(args){');
							scriptTxt.push('');
							scriptTxt.push('    // 待实现');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('}');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/** ******************************* 以下为共公函数 ******************************* */');
							scriptTxt.push('include seeyon.common.groovy;');
							scriptTxt.push('include snail.common.trigger2.groovy;');
							scriptTxt.push('');
							
							return scriptTxt.join('\r\n');
						})());
						
					}else{
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'text/x-groovy',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true,
						indentUnit: 4,
						extraKeys: {
							'Ctrl': 'autocomplete'
						},
						hintOptions: {
							completeSingle: false,
							hint: $.codemirror.groovyShowHint,
							word: {
								__WORD_LIST__: [
									'getObjBySQL(sqlStr, closure, nodata_closure=null)', 'getObjBySQL(sqlStr, args, closure, nodata_closure)', 
									'getListBySQL(sqlStr, closure, nodata_closure=null)', 'getListBySQL(sqlStr, args, closure, nodata_closure)',
									'getSQLClient()', 'sendMessage(txt, receiver=null)', 'logger(txt)', 'GLOBALS(key, value=null)', 'NVL(obj, Object... obj2)',
									'sendTriggerMessage(txt, receiver=null)', 'getBusinessBillsData()', 'getBusinessAttributeValue(key, defaultValue=null)',
									'setBusinessAttributeData(key, value)', 'getTime(key, defaultValue=null)', 'getTimeText(key, defaultValue=null)',
									'getDate(key, defaultValue=null)', 'getDateText(key, defaultValue=null)', 'getEnumShowvalue(key, defaultValue=null)',
									'getEnumValue(key, defaultValue=null)', 'getEnumCode(key, defaultValue=null)', 'getMember(key, defaultValue=null)',
									'getMemberCode(key, defaultValue=null)', 'getLoginName(key, defaultValue=null)', 'getDeptName(key, defaultValue=null)',
									'getDeptCode(key, defaultValue=null)', 'getUnitName(key, defaultValue=null)', 'getUnitCode(key, defaultValue=null)',
									'getPostName(key, defaultValue=null)', 'getPostCode(key, defaultValue=null)', 'getLevelName(key, defaultValue=null)',
									'getLevelCode(key, defaultValue=null)', 'getNumber(key, defaultValue=null)', 'getString(key, defaultValue=null)',
									'getValue(key, defaultValue=null)', 'setValue(key, value)'
								]
							}
						}
					});
					
					editor.on('keypress', function(){
						//编译器内容更改事件
						editor.showHint();
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script, isNew){
				
				script = (_script ? decodeURIComponent(_script) : '');
				
				if(isNew){
					
					// 加时间戳
					script = script.replace(/(\#\!\/snail\/common\/utils\s+groovy\s+[a-zA-Z][a-zA-Z_0-9]+)/, ('$1_' + $.dateFormat(new Date(), 'yyyyMMddHHmmssS')));
				}
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return encodeURIComponent(editor ? editor.getValue() : script)
			},
			getOriginalValue: function(){
				return (editor ? editor.getValue() : script);
			}
		}
	})();

	/**
	 * 修改配置时，系统会自动把上次存储的配置值（字符串），返还给你，具体填充到form自行负责
	 */
	function initParams(){
				
		app = new Vue({
			el: '#app',
			data: {
				style:{
					selectedIndex: 'first'
				},
				basic:{
					isInitCompleted: false
				},
				businessBillsSelect:{
					props: {}, 
					options: [
						{ id: '...', value: '...', label: '...' }
					]
				},
				formFieldSelect:{
					props: {}, 
					groups:[
						{	
							label: '默认',
							options: [
								{ id: '...', value: '...', label: '...' }
							]
						}
					]
				},
				businessFieldTable:{
					props: {
						children: 'children', hasChildren: 'hasChildren'
					}, 
					data: [{
						id: null,
						title: '...',
						key: '...',
						inKey: null,
						type: null,
						defaultValue: null
					}]
				},
				businessAttributeTable:{
					props: {
						children: 'children', hasChildren: 'hasChildren'
					}, 
					data: [{
						id: null,
						title: '...',
						key: '...',
						inKey: null,
						type: null,
						defaultValue: null
					}]
				},
				formData:{
					businessBills: null
				},
				isEvent: false
			},
			methods:{
				init: function(){
					
					this.loadBusinessBillsSelectTree();

					this.initFields();
					
					this.initConfig();
					
					this.basic.isInitCompleted = true;
					
				},
				initFields: function(){

					var _this = this;
					
					$.http.get({
						url:'/seeyon/snail/form.do?method=getFormInfo',
						header: {'Accept': 'application/json'},
						data:{id: getFormId()},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){

								if(result.data){
									
									var tableInfo = result.data.info;
									
									_this.formFieldSelect.groups = [{
										key: tableInfo.front_formmain.tableName,
										label: '主表',
										options: []
									}];
									
									tableInfo.front_formmain.fieldInfo.forEach(function(field){
											
										_this.formFieldSelect.groups[0].options.push({ id: field.id, value: (tableInfo.front_formmain.tableName + '.' + field.name), label: field.display });
									});
									
									var index = 0;
									
									tableInfo.formsons.forEach(function(tableInfo){
										
										var tableName = tableInfo.tableName;
										
										_this.formFieldSelect.groups.push({
											key: tableName,
											label: '子表-' + tableInfo.display,
											options: []
										});
										
										index++;
										
										tableInfo.fieldInfo.forEach(function(field){
											
											_this.formFieldSelect.groups[index].options.push({ id: field.id, value: (tableName + '.' + field.name), label: field.display });
										});
									});
									
									
								}else{
									_this.businessBillsSelect.options = [];
								}
															
							}else{
								alert('表单不存在！！！');
							}
						},
						onerror: function(responseText, status, xhr){
							alert(responseText);
						}
					});
				},
				initConfig(){
					
					var data = getTransParams();
					
					if($.isBlank(data.configValue)){
						
						return ;
					}
					
					var config = $.toJSON(data.configValue);
					
					this.formData.businessBills = config.code;
					this.businessFieldTable.data = config.fieldInfo;
					this.businessAttributeTable.data = config.attributeInfo;

					jsonCodeMirror.setValue(config.configSourceCode);
					groovyCodeMirror.setValue(config.script);
					
					this.isEvent = (config.isEvent == undefined ? false : config.isEvent);
				},
				loadBusinessBillsSelectTree: function(){
					
					var _this = this;
					
					$.http.get({
						url:'/seeyon/snail/ftrigger.do?method=tree',
						header: {'Accept': 'application/json'},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){

								if(result.data){
									
									_this.businessBillsSelect.options = result.data;
									
								}else{
									_this.businessBillsSelect.options = [];
								}
															
							}else{
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							alert(responseText);
						}
					});
				},
				loadBusinessBillsConfig: function(code){
					
					var _this = this;
					
					$.http.get({
						url:'/seeyon/snail/ftrigger.do?method=getConfig',
						header: {'Accept': 'application/json'},
						data: {code: code},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){

								if(result.data){
									
									_this.businessFieldTable.data = _this.mergeConfigListData(result.data.config.fieldInfo, _this.businessFieldTable.data);

									_this.businessAttributeTable.data = _this.mergeConfigListData(result.data.config.attributeInfo, _this.businessAttributeTable.data);

									jsonCodeMirror.setValue(result.data.configSourceCode);
									groovyCodeMirror.setValue(result.data.script, true);
									
								}else{
									
									_this.businessFieldTable.data = [];
									_this.businessAttributeTable.data = [];
								}
																
							}else{
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							alert(responseText);
						}
					});
				},
				onBusinessBillsChange: function(value){
					
					this.loadBusinessBillsConfig(value);
					
				},
				onTabsBeforeChange: function(activeName, oldActiveName){
					
					if('thirdly' == oldActiveName){
						
						var config = jsonCodeMirror.getOriginalValue();
						
						if($.isBlank(config)){
							return true;
						}
						
						try{
							
							config = $.toJSON(config);
							
							this.businessFieldTable.data = this.mergeConfigListData(config.fieldInfo, this.businessFieldTable.data);

							this.businessAttributeTable.data = this.mergeConfigListData(config.attributeInfo, this.businessAttributeTable.data);
							
						}catch(err){
							
							alert(err);
							
							return false;
						}
					}
					
					return true;
				},
				onTabsChange: function(tab, event){
					
					if('thirdly' == tab.name){
						
						jsonCodeMirror.init();
						
					}else if('fourthly' == tab.name){

						groovyCodeMirror.init();
					}
				},
				onReset: function(){
				
					this.loadBusinessBillsConfig(this.formData.businessBills);
					
				},
				/**
				 * 更新历史触发
				 */
				onUpdateHisotory: function(){
					
					var data = {
							code: this.formData.businessBills,
							fieldInfo: this.businessFieldTable.data,
							attributeInfo: this.businessAttributeTable.data,
							script: groovyCodeMirror.getValue(),
							updateDate: $.dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss')
						};
					
					data = $.toJSONString(data);
					
					$.http.post({
						url:'/seeyon/snail/ftrigger.do?method=updateConfigToFormTriggerRecord',
						header: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
						data: {
							triggerId: getTriggerId(),
							formId: getFormId(),
							configvalue: data
						},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){
								
								alert("更新完成，SIZE: " + result.data);
								
							}else{
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							console.log(responseText);
						}
					});
				},
				/**
				 * 发布事件实现
				 */
				onIssueEventProcessor: function(){
					
					var _this = this;
					
					$.http.post({
						url:'/seeyon/snail/dip/setting.do?method=issueEventProcessor',
						header: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
						data: {
							triggerId: getTriggerId(),
							formId: getFormId()
						},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){
								
								_this.isEvent = true;
								
								alert("发布完成，SIZE: " + result.data + "\t（注意：*** 请保存数据 ***）");
								
							}else{
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							console.log(responseText);
						}
					});
				},
				/**
				 * 合并配置信息
				 */
				mergeConfigListData: function(listData, oldListData){
					
					if(null == listData || 1 > listData.length){
						
						return oldListData;
					}
					
					var _mergeListData = function (listData, oldListData, prefix){
						
						var id = null;
						var oldData = null;
						
						for(var i=0,len=listData.length; i<len; i++){
							
							id = listData[i]['id'] = (prefix + listData[i].key);
							
							if(!listData[i].type){
								listData[i]['type'] = 'string';
							}
							
							if(!listData[i].defaultValue){
								listData[i]['defaultValue'] = '';
							}
							
							if(!listData[i].desc){
								listData[i]['desc'] = '';
							}
							
							if(oldListData){
								
								oldData = null;
								
								for(var j=0,jlen=oldListData.length; j<jlen; j++){
									
									if(id == oldListData[j].id){
										
										oldData = oldListData[j];
										
										break;
									}
								}
								
								if(oldData){

									listData[i]['inKey'] = oldData.inKey;
									listData[i]['defaultValue'] = oldData.defaultValue;
									
									listData[i]['type'] = (('object' == listData[i]['type'] || 'array' == listData[i]['type']) ? listData[i]['type'] : oldData.type);
								}
							}
							
							if(!listData[i].children || 0 == listData[i].children.length){
								continue;
							}
							
							_mergeListData(listData[i].children, (oldData ? oldData.children : null), (id + '.'));
						}
						
						return listData;
					}
									
					return _mergeListData(listData, oldListData, '');
				}
			},
			created: function(){
				this.init();
			}
		});

	}

	$.extend('app',{
		
		init: function(){
			
			initWindow();
			
			initParams();
		}
	});

	/**
	 *	保存返回数据
	 */
	win['OK'] = function() {
		
		if(app && null == app.formData.businessBills){
			
			alert('未选择【业务单据】');
			
			return 'error'; /* 返回error，则阻止窗体关闭 */
		}
		
		var data = {
			code: (app ? app.formData.businessBills : null),
			fieldInfo: (app ? app.businessFieldTable.data : []),
			attributeInfo: (app ? app.businessAttributeTable.data : []),
			configSourceCode: jsonCodeMirror.getValue(),
			script: groovyCodeMirror.getValue(),
			isEvent: (app ? app.isEvent : false)
		};
		
	    return $.toJSONString(data);
	}
})(Snail, window, document);